﻿using System;

using Datagility.Shpt.SPDocMirror.Settings;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.WebControls;

namespace Datagility.Shpt.SPDocMirror.UI.Layouts.Datagility.Shpt.SPDocMirror.UI
{
    public partial class MirrorSettingsPage : LayoutsPageBase
    {
        SPSite siteCollection;
        MirrorJobSettings settings;
        string libId = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            //Get the Id of the current list from the query string
            if (this.Request.QueryString["listid"] != null)
            {
                libId = this.Request.QueryString["listid"];

                //Get the stored settings
                siteCollection = SPContext.Current.Web.Site;
                settings = MirrorJobSettingsFactory.GetMirrorJobSettings(siteCollection.Url);

                if (!this.IsPostBack)
                {
                    //Set control values based on the read settings
                    if (settings.LibrariesEnabled != null)
                        chkEnabled.Checked = settings.LibrariesEnabled.Contains(libId);
                }
            }
        }

        protected override void OnInit(EventArgs e) 
        { 
            base.OnInit(e);

            ((DialogMaster)this.Page.Master).OkButton.Click += new EventHandler(this.OkButton_Click); 
        }  

        protected void OkButton_Click(object sender, EventArgs e) 
        {
            //Update the LibrariesEnabled setting
            if (this.chkEnabled.Checked == true)
            {
                if (settings.LibrariesEnabled == null ||
                    !settings.LibrariesEnabled.Contains(libId))
                {
                    settings.LibrariesEnabled += (libId + ";");
                }
            }
            else
            {
                if (settings.LibrariesEnabled != null && 
                    settings.LibrariesEnabled.Contains(libId))
                {
                    int idIndex = settings.LibrariesEnabled.IndexOf(libId);
                    settings.LibrariesEnabled = settings.LibrariesEnabled.Remove(idIndex, libId.Length + 1);
                    if (settings.LibrariesEnabled.Length == 0)
                        settings.LibrariesEnabled = null;
                }
            }

            MirrorJobSettingsFactory.SetMirrorJobSettings(siteCollection.Url, settings);

            this.SendResponseForPopUI();
        }
    }
}
